package com.ftg.learn.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.ftg.learn.entity.SysUser;
import com.ftg.learn.mapper.SysUserMapper;
import com.ftg.learn.service.SysUserService;
import com.ftg.learn.util.R;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;

/**
 * @author 布衣
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    private final String salt = "$apr1$kjxnd";

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public R<String> login(String account, String password) {
        SysUser user = sysUserMapper.findByAccount(account, Md5Crypt.apr1Crypt(password,salt));
        if(Objects.isNull(user)){
            return R.fail("用户名或者密码错误!!!");
        }
        String token = JWT.create().withClaim("id", user.getId())
                    .withClaim("account", user.getAccount())
                    .sign(Algorithm.HMAC256(user.getPassword()));
        return R.ok(token);
    }

    @Override
    public R<Integer> register(String account, String password) {
        int num = sysUserMapper.register(account, Md5Crypt.apr1Crypt(password,salt));
        return R.ok(num);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R<Boolean> assignRole(Integer userId, List<Integer> roleIds) {
        for (Integer roleId : roleIds) {
            sysUserMapper.assignRole(userId,roleId);
        }
        return R.ok(true);
    }
}
